package com.uu.ssm.controller;

import com.uu.ssm.constants.Constants;
import com.uu.ssm.model.dao.WorkerMapper;
import com.uu.ssm.model.vo.Worker;
import org.springframework.beans.factory.annotation.Autowired;
import com.uu.ssm.model.service.WorkerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class WorkerController {
    @Autowired
    private WorkerService service;
    @Autowired
    private WorkerMapper workerMapper;


    /**
     * 处理登录请求
     *
     * @return 重定向到登录页面的视图名称
     */
    @RequestMapping(Constants.ACTION_LOGIN)
    public String login() {
        return Constants.VIEW_LOGIN;
    }

    /**
     * 处理登录请求
     *
     * @return 重定向到登录页面的视图名称
     */
    @RequestMapping(Constants.ACTION_REGISTER)
    public String register() {
        return Constants.VIEW_REGISTER;
    }


    /**
     * 处理注册成功请求
     *
     * @param worker 注册表单提交的工人信息
     * @return 根据注册结果返回不同的视图和信息
     */
    @RequestMapping(Constants.ACTION_REGISTER_SUCCESS)
    public ModelAndView registerSuccess(Worker worker) {
        ModelAndView modelAndView = new ModelAndView();
        int result = service.register(worker);

        switch (result) {
            case Constants.NUM_MINUS_ONE:
                modelAndView.setViewName(Constants.VIEW_REGISTER);
                modelAndView.addObject(Constants.MESSAGE_KEY_INSERT,
                        Constants.MESSAGE_INFO_INSERT_NULL);
                break;
            case Constants.NUM_MINUS_TWO:
                modelAndView.setViewName(Constants.VIEW_REGISTER);
                modelAndView.addObject(Constants.MESSAGE_KEY_INSERT,
                        Constants.MESSAGE_INFO_INSERT_EXIST);
                break;
            default:
                modelAndView.setViewName(Constants.VIEW_LOGIN);
        }
        return modelAndView;
    }

    @RequestMapping(Constants.ACTION_LOGIN_SUCCESS)
    public ModelAndView loginSuccess(Worker worker) {
        ModelAndView modelAndView = new ModelAndView();
        if (service.login(worker)) {
            modelAndView.setViewName(Constants.VIEW_SUCCESS);
            modelAndView.addObject(Constants.WORKER_LIST, service.selectAllWorkers());
        } else {
            modelAndView.setViewName(Constants.VIEW_LOGIN);
            modelAndView.addObject(Constants.MESSAGE_KEY_INSERT, Constants.MESSAGE_INFO_LOGIN);
        }
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping(Constants.ACTION_UPDATE_WORKER)
    public void updateWorker(Worker worker) {
        service.updateWorker(worker);
    }

    @ResponseBody
    @RequestMapping(Constants.ACTION_DELETE_WORKER)
    public void deleteWorker(Integer id) {
        service.deleteWorker(id);
    }
}
